/**
 * 查看、编辑地区
 */

import React, { useState, useEffect } from 'react';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import { Checkbox, Divider, Empty, message, Button, Form, Select, Input, Tooltip } from 'antd';
import { cloneDeep, find, findIndex } from 'lodash';
import { getAllArea } from '@/services/common';
import { seeSelectedAreas, updateMatchRule, getNetworkListForMatch, getMatchExpressList, saveMatchRule, getAvailableList, getExpressAvailableList } from '../../service';
import styles from './index.module.less';
const { Option } = Select;

export default ({ item, visible, handleOk, handleCancel }) => {
  
  const { type='look', matchConfig } = item; 

  //省市区数据
  const [ data, setData ] = useState([]);
  const [ form ] = Form.useForm();
  const [ loading, setLoading ] = useState(false);

  //当前展示的省id
  const [ provinceId, setProvinceId ] = useState(undefined);
  
  //当前展示的市id
  const [ cityId, setCityId ] = useState(undefined);
  
  //已经选中的区域列表，分省市区维度
  const [ selectData, setSelectData ] = useState([]);
  
  //快递公司列表
  const [ expressList, setExpressList ] = useState([]);

  //网点列表
  const [ networkList, setNetworkList ] = useState([])

  useEffect(() => {
    if(visible) {
      if(type == 'add') {
        getExpressdata();
      } else if(type == 'update') {
        handleGetUpdateData();
      } else {
        handleGetLookData();
      }
      form.resetFields();
    }
  }, [visible])

  const handleGetLookData = () => {
    const List1 = getAllArea();
    const List2 = seeSelectedAreas({
      expressNetworkId: item.id
    })
    setLoading(true);
    Promise.all([List1, List2]).then(res => {
      if(res[0].success && res[1].success) {
        setData(res[0].data);
        setSelectData(res[1].data);
        if(res[1].data.length > 0) {
          const arr = res[1].data;
          const arr1 = arr[0].childs;
          if(arr && arr.length > 0) {
            setProvinceId(arr[0].id);
          } 
          if(arr1 && arr1.length > 0) {
            setCityId(arr1[0].id);
          }
        } 
      }
      setLoading(false);
    }).catch(err => {
      setLoading(false);
      console.log(err, 'err');
    })
  }

  const handleGetUpdateData = () => {
    const List1 = getAvailableList({
      expressId: matchConfig.expressId,
      expressNetworkId: item.id
    });
    const List2 = seeSelectedAreas({
      expressNetworkId: item.id
    })
    setLoading(true);
    Promise.all([List1, List2]).then(res => {
      setLoading(false);
      if(res[0].success && res[1].success) {
        setData(res[0].data);
        setSelectData(res[1].data);
        if(res[1].data.length > 0) {
          const arr = res[1].data;
          const arr1 = arr[0].childs;
          if(arr && arr.length > 0) {
            setProvinceId(arr[0].id);
          } 
          if(arr1 && arr1.length > 0) {
            setCityId(arr1[0].id);
          }
        } 
      }
    }).catch(err => {
      setLoading(false);
      console.log(err);
    })
  }

  const onOk = () => {
    if(loading) {
      return false;
    }
    if(type == 'update') {
      updateMatchData();
    } else {
      form.validateFields().then(val => {
        updateMatchData(val);
      })
    }   
  }

  const getExpressdata = async () => {
    setLoading(true);
    const res = await getMatchExpressList();
    if(res.success) {
      setExpressList(res.data);
    }
    setLoading(false);
  }

  //编辑/新增
  const updateMatchData = async (val) => {
    setLoading(true);
    const list = [];
    for(let i in selectData) {
      const arr = selectData[i].childs;
      for(let k in arr) {
        const arr1 = arr[k].childs;
        arr1.map(v => {
          list.push(v.id);
        })
      }
    }
    let res;
    if(type == 'update') {//编辑
      res = await updateMatchRule({
        areaIds: list,
        expressId: matchConfig.expressId,
        expressName: matchConfig.expressName,
        id: item.id,
        networkId: item.networkId
      })
    } else {
      res = await saveMatchRule({
        areaIds: list,
        expressId: val.expressId,
        expressName: find(expressList, [ 'id', val.expressId ]).name,
        networkId: val.networkId
      })
    }
    if(res.success) {
      message.success('设置成功！');
      handleOk();
      onCancel();
    }
    let timer = setTimeout(() => {
      setLoading(false);
      clearTimeout(timer);
      timer = null;
    }, 300)
  }

  const onCancel = () => {
    handleCancel();
    setData([]);
    setProvinceId(undefined);
    setCityId(undefined);
    setSelectData([]);
    setExpressList([]);
    setNetworkList([]);
  }

  //选择省份
  const handleSelectProvince = (e, id) => {
    if(id > 100) {
      message.warning('暂不支持该区域');
      return;
    }
    let checked = e.target.checked;
    if(checked) {//全选市
      const obj = find(data, ['id', id]);
      const arr = cloneDeep(selectData);
      const index = findIndex(arr, ['id', id]);
      if(index > -1) {
        arr[index] = obj;
      } else {
        arr.push(obj);
      }
      setSelectData(arr);
      handleClickProvince(id);
    } else {
      const arr = cloneDeep(selectData);
      const index = findIndex(arr, ['id', id]);
      arr.splice(index, 1);
      setSelectData(arr);
      handleClickProvince(id);
    }
  }

  //选择市
  const handleSelectCity = (e, id) => {
    let checked = e.target.checked;
    if(checked) {//全选区
      //查询到省
      const obj = find(data, ['id', provinceId]);
      //查询到市
      const obj1 = find(obj.childs, ['id', id]);

      const index1 = findIndex(selectData, ['id', provinceId]);
      if(index1 > -1) {//如果已选列表包含当前省
        const index2 = findIndex(selectData[index1].childs, ['id', id]);
        const arr = cloneDeep(selectData);
        if(index2 > -1) {//如果已选包含当前市
          arr[index1].childs[index2] = obj1;
        } else {
          arr[index1].childs.push(obj1);
        }
        setSelectData(arr)
      } else {
        const arr = cloneDeep(selectData);
        const arr1 = [];
        arr1.push(obj1);
        const obj = {
          id: provinceId,
          name: find(data, ['id', provinceId]).name,
          childs: arr1,
        }
        arr.push(obj);
        setSelectData(arr);
      } 
    } else {//取消全选
      const arr = cloneDeep(selectData);
      const index1 = findIndex(selectData, ['id', provinceId]);
      const index2 = findIndex(selectData[index1].childs, ['id', id]);
      arr[index1].childs.splice(index2, 1);
      setSelectData(arr);
    }
  }

  //选择区
  const handleSelectArea = (e, id) => {
    let checked = e.target.checked;
    if(checked) {//选择
      const index = findIndex(selectData, ['id', provinceId]);
      if(index > -1) {//已选列表包含当前省
        const index1 = findIndex(selectData[index].childs, ['id', cityId]);
        if(index1 > -1) {//已选列表包含当前市
          const obj = {
            id: id
          }
          const arr = cloneDeep(selectData);
          arr[index].childs[index1].childs.push(obj);
          setSelectData(arr);
        } else {
          const arr = [];
          arr.push({ id: id });
          const obj = {
            id: cityId,
            childs: arr
          }
          const list = cloneDeep(selectData);
          list[index].childs.push(obj);
          setSelectData(list);
        }
      } else {
        const arr = [];
        arr.push({ id });
        const obj = {
          id: cityId,
          childs: arr
        }
        const arr1 = [];
        arr1.push(obj);
        const obj1 = {
          id: provinceId,
          name: find(data, ['id', provinceId]).name,
          childs: arr1
        }
        const list = cloneDeep(selectData);
        list.push(obj1);
        setSelectData(list);
      }
    } else {//取消选择
      const index1 = findIndex(selectData, ['id', provinceId]);
      const index2 = findIndex(selectData[index1].childs, ['id', cityId]);
      const index3 = findIndex(selectData[index1].childs[index2].childs, ['id', id]);
      const arr = cloneDeep(selectData);
      arr[index1].childs[index2].childs.splice(index3, 1);
      setSelectData(arr);
    }
  }

  //查看省份
  const handleClickProvince = (id) => {
    if(id == provinceId) {
      return;
    }
    if(id > 100) {
      message.warning('暂不支持该区域');
      return;
    }
    const arr = find(data, [ 'id', id ]).childs;
    setProvinceId(id);
    setCityId(arr[0].id);
  }

  //查看市
  const handleClickCity = (id) => {
    if(id == cityId) {
      return;
    }
    setCityId(id);
  }

  //判断省是否全选
  const getProvinceChecked = (id) => {
    const index = findIndex(selectData, ['id', id]);
    if(index > -1) {
      const arr1 = find(data, ['id', id]).childs;
      const arr2 = selectData[index].childs;
      if(arr1.length == arr2.length) {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  }

  //判断市是否全选
  const getCityChecked = (id) => {
    const index1 = findIndex(selectData, ['id', provinceId]);
    if(index1 == -1) {
      return false;
    }
    const arr = find(selectData, ['id', provinceId]).childs;
    const index = findIndex(arr, ['id', id]);
    if(index > -1) {
      const arr1 = find(find(data, ['id', provinceId]).childs, ['id', id]).childs;
      const arr2 = find(arr, ['id', id]).childs;
      if(arr1.length == arr2.length) {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  }

  //判断区是否是选择
  const getAreaChecked = (id) => {
    //首先判断是否是否有该省份
    const index1 = findIndex(selectData, ['id', provinceId]);
    if(index1 == -1) {
      return false;
    } else {
      //其次判断是否有该市区
      const index2 = findIndex(selectData[index1].childs, ['id', cityId]);
      if(index2 == -1) {
        return false;
      } else {
        const index3 = findIndex(selectData[index1].childs[index2].childs, ['id', id]);
        if(index3 > -1) {
          return true;
        }
        return false;
      }
    }
  }

  //渲染市列表
  const renderCity = () => {
    if(provinceId && data.length) {
      const list = find(data, ['id', provinceId ]);
      if(list) {
        const arr = list.childs;
        return (
          <div style={{ lineHeight: '32px', overflow: 'auto' }}>
            {
               arr.map(v => (
                <span style={{ margin: '0px 8px', display: 'inline-block' }} key={v.id}>
                  <Checkbox indeterminate={handleSelectAllCity(v.id)} disabled={type == 'look' ? true : false} checked={getCityChecked(v.id)} onClick={e => handleSelectCity(e, v.id)}  />
                  <span className={v.id == cityId ? styles.select : styles.normal} onClick={() => handleClickCity(v.id)} key={v.id}>{v.name}{getCityNum(v.id)}</span>
                </span>
               ))
            }
          </div>
        )
      } else {
        return (
          <div style={{ height: '250px' }}>
            <Empty  description='请选择省份' />
          </div>
        )
      }
    } else {
      return (
        <div style={{ height: '250px' }}>
          <Empty  description='请选择省份' />
        </div>
      )
    }
  }

  //渲染区域列表
  const renderArea = () => {
    if(cityId && data.length > 0) {
      const list = find(data, ['id', provinceId ]);
      if(list) {
        const arr = list.childs;
        const list1 = find(arr, [ 'id', cityId ]);
        if(list1) {
          const arr1 = list1.childs;
          return (
            <div style={{ lineHeight: '32px', overflow: 'auto' }}>
              {
                 arr1.map(v => (
                  <span key={v.id} style={{ margin: '0 8px', display: 'inline-block' }}>
                    <Checkbox disabled={type == 'look' ? true : false} checked={getAreaChecked(v.id)} onClick={e => handleSelectArea(e, v.id)} />
                    <span className={styles.noClick}>{v.name}</span>
                  </span>
                ))
              }
            </div>
          )
        } else {
          return (
            <div>
              <Empty description='请选择市' />
            </div>
          )
        }
      } else {
        return (
          <div>
            <Empty description='请选择市' />
          </div>
        )
      }
    } else {
      return (
        <div>
          <Empty description='请选择市' />
        </div>
      )
    }
  }


  //计算该省份选择市的数量
  const getProvinceNum = id => {
    const obj = find(selectData, ['id', id]);
    if(obj) {
      return `（${obj.childs.length}）`;
    }
    return `（0）`;
  }

  //计算该城市选择区的数量
  const getCityNum = id => {
    const obj = find(selectData, ['id', provinceId]);
    if(obj) {
      const obj1 = find(obj.childs, ['id', id]);
      if(obj1) {
        return `（${obj1.childs.length}）`;
      }
      return `（0）`;
    }
    return `（0）`;
  }

  //显示省是否全选
  const handleSelectAllProvince = (id) => {
    let num2 = find(selectData, ['id', id]) ? find(selectData, ['id', id]).childs.length : undefined;
    if(num2) {
      let num1 = find(data, ['id', id]).childs.length;
      if(num2 < num1) {
        return true;
      }
      return false;
    }
    return false;
  }

  //显示市是否全选
  const handleSelectAllCity = (id) => {
    const cityData = find(selectData, ['id', provinceId]);
    if(cityData) {
      let num2 = find(cityData.childs, ['id', id]) ? find(cityData.childs, ['id', id]).childs.length : undefined;
      if(num2) {
        const cityData1 = find(data, ['id', provinceId]).childs;
        let num1 = find(cityData1, ['id', id]).childs.length;
        if(num2 < num1) {
          return true;
        }
        return false;
      }
    } else{
      return false;
    }
  }

  const handleSelectExpress = (val) => {
    setLoading(true);
    const List1 = getExpressAvailableList({
      expressId: val
    })
    const List2 = getNetworkListForMatch({
      expressId: val
    })
    Promise.all([List1, List2]).then(res => {
      if(res[0].success && res[1].success) {
        setData(res[0].data);
        setNetworkList(res[1].data);
      }
      setLoading(false);
    }).catch(err => {
      setLoading(false);
      console.log(err);
    })
  }


  const getFooter = () => {
    if(type == 'look') {
      return [
        <Button key='save' onClick={onCancel}>关闭</Button>
      ]
    } else {
      return [
        <Button key='cancel' onClick={onCancel}>取消</Button>,
        <Button key='save' type='primary' onClick={onOk}>确定</Button>
      ]
    }
  }

  const options1 = expressList.map(d => 
    <Option key={d.id} value={d.id}>
      <Tooltip title={d.name}>
        {d.name}
      </Tooltip>
    </Option>
  );
  const options2 = networkList.map(d => 
    <Option key={d.id} value={d.id}>
      <Tooltip title={d.name}>
        {d.name}
      </Tooltip>
    </Option>
  );

  const renderForm = () => {
    if(type == 'look' || type == 'update') {
      return (
        <Form form={form} 
          name='select-area-disabled'
          layout="inline" 
          style={{ marginBottom: '24px' }} 
          key={matchConfig.expressName} 
          initialValues={{
            expressId: matchConfig.expressName,
            networkId: item.networkName
          }}
          >
          <Form.Item
            name="expressId"
            label="快递公司"
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            name="networkId"
            label="快递网点"
          >
            <Input  disabled />
          </Form.Item>
        </Form>
      )
    }
    return (
      <Form form={form} name='set-express' layout="inline" style={{ marginBottom: '24px' }} >
        <Form.Item
          name="expressId"
          label="快递公司"
          rules={[ { required: true, message: '快递公司必选' } ]}
        >
          <Select placeholder='请选择快递公司' showSearch optionFilterProp="children" style={{ width: '240px' }} onChange={handleSelectExpress}>
            {options1}
          </Select>
        </Form.Item>
        <Form.Item
          name="networkId"
          label="快递网点"
          rules={[{ required: true, message: '快递网点必选' }]}
        >
          <Select placeholder='请选择快递网点'  showSearch optionFilterProp="children" style={{ width: '240px' }}>
            {options2}
          </Select>
        </Form.Item>
      </Form>
    )
  }

  const renderBody = () => {
    if(type == 'add') {
      const val = form.getFieldValue('expressId');
      if(val) {
        if(data.length > 0) {
          return (
            <div className="flex">
              <div style={{ width: '260px', overflow: 'auto' }}>
                <h3>省列表：</h3>
                <div style={{ display: 'flex', flexWrap: 'wrap' }}>
                  {
                    data.map(v => (
                      <div key={v.id} style={{ width: '120px', margin: '2px 4px'}}>
                        <Checkbox indeterminate={handleSelectAllProvince(v.id)} checked={getProvinceChecked(v.id)} disabled={type == 'look' ? true : false} onClick={e => handleSelectProvince(e, v.id)} />
                        <span  className={ v.id == provinceId ? styles.select : styles.normal } onClick={() => handleClickProvince(v.id)}  key={v.id}>{v.name}{getProvinceNum(v.id)}</span>
                      </div>
                    ))
                  }
                </div>
              </div>
              <Divider type='vertical' style={{ height: '520px', marginRight: '24px', borderWidth: '4px' }} />
              <div style={{ flex: '1' }}>
                <h3>市列表：</h3>
                {renderCity()}
                <Divider />
                <h3>区列表：</h3>
                {renderArea()}
              </div>
            </div>
          )
        } else {
          return (
            <Empty description='当前快递公司无可用区域' />
          )
        }
      } else {
        return (
          <Empty description='请先选择快递公司' />
        )
      }
    } else {
      return (
        <div className="flex">
          <div style={{ width: '260px', overflow: 'auto' }}>
            <h3>省列表：</h3>
            <div style={{ display: 'flex', flexWrap: 'wrap' }}>
              {
                data.map(v => (
                  <div key={v.id} style={{ width: '120px', margin: '2px 4px'}}>
                    <Checkbox indeterminate={handleSelectAllProvince(v.id)} checked={getProvinceChecked(v.id)} disabled={type == 'look' ? true : false} onClick={e => handleSelectProvince(e, v.id)} />
                    <span  className={ v.id == provinceId ? styles.select : styles.normal } onClick={() => handleClickProvince(v.id)}  key={v.id}>{v.name}{getProvinceNum(v.id)}</span>
                  </div>
                ))
              }
            </div>
          </div>
          <Divider type='vertical' style={{ height: '520px', marginRight: '24px', borderWidth: '4px' }} />
          <div style={{ flex: '1' }}>
            <h3>市列表：</h3>
            {renderCity()}
            <Divider />
            <h3>区列表：</h3>
            {renderArea()}
          </div>
        </div>
      )
    }
  }

  return (
    <CommonModal
      title={matchConfig.title || '查看地区'}
      visible={visible}
      width='900px'
      onCancel={onCancel}
      footer={getFooter()}
    >
      { renderForm() }
      { renderBody() }
      <CommonLoading loading={loading} />
    </CommonModal>
  )
}